package com.leyou.user.service;

import com.leyou.common.constant.LyConstants;
import com.leyou.common.constant.MQConstants;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    public Boolean checkData(String data, Integer type) {
        User record = new User();
        //根据type判断输入的值是什么
        switch (type){
            case 1:
                record.setUsername(data);
                break;
            case 2:
                record.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        //判断用户名和手机号是否可用，其实就是判断数据库中是否已经有了输入的用户名或手机号
        int count = userMapper.selectCount(record);
        return count==0;
    }

    public void sendCheckCode(String phone) {
        //生成6为纯数字验证码【不能有字母】
        String code = RandomStringUtils.randomNumeric(6);
        //把验证码存储到redis中，设置过期时间，一般企业中都是在15分钟到2小时。
        redisTemplate.opsForValue().set(LyConstants.REDIS_KEY_PRE+phone, code, 2, TimeUnit.DAYS);
        //封装mq消息对象 Map<String, String> smsParam
        Map<String, String> smsParam = new HashMap<>();
        smsParam.put("phone", phone);
        smsParam.put("code", code);
        //想队列中发送消息
        amqpTemplate.convertAndSend(MQConstants.Exchange.SMS_EXCHANGE_NAME,
                MQConstants.RoutingKey.VERIFY_CODE_KEY, smsParam);
    }

    public void register(User user, String code) {
        //获取redis中的验证码
        String redisCode = redisTemplate.opsForValue().get(LyConstants.REDIS_KEY_PRE + user.getPhone());
        //判断用户输入的验证码是否正确
        if(!StringUtils.equals(code, redisCode)){
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        //如果验证码没问题，对密码进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //保存数据
        int count = userMapper.insertSelective(user);
        if(count!=1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    public User findUserByUsernameAndPassword(String username, String password) {
        //根据用户名查询用户对象
        User record = new User();
        record.setUsername(username);
        User user = null;
        try {
            user = userMapper.selectOne(record);
        }catch (Exception e){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        if(user==null){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        if(!passwordEncoder.matches(password, user.getPassword())){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        return user;
    }
}
